package com.tc.netty;

import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;

/**
 * @Auther: tianchao
 * @Date: 2022/2/11 11:26
 * @Description: promise同样也是个结果的容器
 */
@Slf4j
public class TestNettyPromise {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(2);
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        final EventLoop eventLoop = eventLoopGroup.next();
        DefaultPromise<Integer> promise = new DefaultPromise<>(eventLoop);
        new Thread(()->{
            try {
                int i = 1/0;
                log.debug("set...");
                promise.setSuccess(1);
            }catch (Exception e){
                e.printStackTrace();
                promise.setFailure(e);
            }finally {
                countDownLatch.countDown();
            }
        }).start();
        new Thread(()->{
            try {
                log.debug("result: {}",promise.get());

            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
        }).start();
        countDownLatch.await();
        log.debug("main end");
    }
}
